package com.hw.rediscache.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @program: spring-data-redis-cache
 * @description: 缓存key的生成类
 * @author: hewei
 * @date: 2021-09-13 18:30
 **/

@Slf4j
@Component
public class CacheKeyGenerator implements KeyGenerator {

    @Value("${cache.prefix}")
    private String prefix;

    @Override
    public Object generate(Object target, Method method, Object... params) {
        StringBuilder key = new StringBuilder().append(prefix);
        Cacheable cacheable = method.getAnnotation(Cacheable.class);
        if (null!=cacheable
                && !StringUtils.isEmpty(cacheable.value().toString())
                && cacheable.value().length > 0)
        {
            key.append(cacheable.value()[0]);
        }
        Arrays.stream(params).filter(m->{
            return m != null;
        }).forEach(m->{
            key.append("=")
                    .append(JSON.toJSONString(m));
        });

        log.info(">> 缓存key: {}", key);

        return key.toString();
    }
}